import React, { useState, useImperativeHandle, useRef, useEffect } from 'react'
import { Modal, Input, Form } from 'antd'

function TableModal (props, ref) {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [form] = Form.useForm()
  const [isAdd, setIsAdd] = useState('')
  useEffect(() => {
    console.log(props.record)
    form.setFieldsValue({
      Name: props.record.name,
      Address: props.record.address,
      Age: props.record.age
    })
  })

  useImperativeHandle(ref, () => {
    return {
      showModal (e) {
        setIsAdd(e)
        setIsModalVisible(!isModalVisible)
      }
    }
  })
  function handleCancel () {
    setIsModalVisible(!isModalVisible)
    // form.resetFields()
    props.getValue({ cancel: 'cancel' })
  }

  function handleOk () {
    let NewObj = form.getFieldsValue()
    console.log(isAdd)
    if (isAdd) {
      props.getValue(NewObj) //获取表单数据，传递给父组件
    } else {
      props.getValue({ ...NewObj, key: props.record.key }) //获取表单数据，传递给父组件
    }
    // form.resetFields()
    setIsModalVisible(!isModalVisible)
  }

  return (
    <div>
      <Modal
        title='添加'
        visible={isModalVisible}
        onOk={() => {
          handleOk()
        }}
        onCancel={() => {
          handleCancel()
        }}
        forceRender={true}
      >
        <Form
          name='basic'
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          autoComplete='off'
          form={form}
        >
          <Form.Item
            label='Name'
            name='Name'
            rules={[
              {
                required: true,
                message: 'Please input your name'
              }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item label='Address' name='Address'>
            <Input />
          </Form.Item>

          <Form.Item label='Age' name='Age'>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
export default React.forwardRef(TableModal)
